<!-- 人口统计信息 导入 / 手动上传 demographicImport -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>人口信息 导入 / 手动上传</h3>
        </el-divider>

        <el-row :gutter="12">
          <el-col :span="24" style="margin-bottom:12px;">
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>文件导入（XLSX ）</span>
              </div>

              <el-form-item>
                <el-upload
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  accept=".xlsx,.xls"
                  action=""
                >
                  <el-button type="primary">选择并导入 文件（.xlsx）</el-button>
                </el-upload>
                <div class="hint" style="margin-top:8px;color: #999;">
                  支持 .xlsx/.xls 。表头请使用字段名（见模板）。
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="success" :loading="loading" @click="triggerSampleXlsxDownload">下载 XLSX 模板</el-button>
              </el-form-item>
            </el-card>
          </el-col>

          <el-col :span="24">
            <!-- 手动输入（可多条） -->
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>手动输入并上传（可多条）</span>
              </div>

              <div style="margin-bottom:12px;">
                <el-button type="primary" @click="addRow">新增一条</el-button>
              </div>

              <div v-for="(row, idx) in manualList" :key="idx" style="margin-bottom:12px;">
                <el-card shadow="never">
                  <div slot="header" class="clearfix">
                    <span>记录 {{ idx + 1 }}</span>
                    <el-button type="danger" circle icon="el-icon-delete" style="float:right" size="mini" @click="removeRow(idx)" />
                  </div>

                  <el-form ref="manualForm" :model="row" label-width="140px" size="small" label-position="left" :rules="formRules">
                    <el-row :gutter="12">
                      <!-- 将所有字段展示为可输入项，左右两列布局 -->
                      <el-col :span="12">
                        <el-form-item label="编号">
                          <el-input v-model="row.number" />
                        </el-form-item>
                        <el-form-item label="姓名">
                          <el-input v-model="row.name" />
                        </el-form-item>
                        <el-form-item label="病案号" prop="medicalRecordNumber">
                          <el-input v-model="row.medicalRecordNumber" />
                        </el-form-item>
                        <el-form-item label="性别">
                          <el-select v-model="row.gender" placeholder="请选择性别" style="width:100%">
                            <el-option label="男" value="男" />
                            <el-option label="女" value="女" />
                          </el-select>
                        </el-form-item>
                        <el-form-item label="身高">
                          <el-input-number v-model="row.height" :min="0" /> <span>cm</span>
                        </el-form-item>
                        <el-form-item label="体重">
                          <el-input-number v-model="row.weight" :min="0" /> <span>kg</span>
                        </el-form-item>
                        <el-form-item label="职业">
                          <el-input v-model="row.job" />
                        </el-form-item>
                        <el-form-item label="年龄">
                          <el-input-number v-model="row.age" :min="0" />
                        </el-form-item>
                        <el-form-item label="电话">
                          <el-input v-model="row.phone" />
                        </el-form-item>
                        <el-form-item label="国籍">
                          <el-input v-model="row.nationality" />
                        </el-form-item>
                        <el-form-item label="出生日期">
                          <el-date-picker
                            v-model="row.birthDate"
                            type="date"
                            placeholder="选择日期"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            style="width:100%"
                          />
                        </el-form-item>
                        <el-form-item label="出生地">
                          <el-input v-model="row.birthPlace" />
                        </el-form-item>
                        <el-form-item label="民族">
                          <el-input v-model="row.ethnicity" />
                        </el-form-item>
                        <el-form-item label="籍贯">
                          <el-input v-model="row.origin" />
                        </el-form-item>
                        <el-form-item label="身份证号码">
                          <el-input v-model="row.idNumber" />
                        </el-form-item>
                        <el-form-item label="现居住地">
                          <el-input v-model="row.currentAddress" />
                        </el-form-item>
                        <el-form-item label="现居住地邮编">
                          <el-input v-model="row.currentAddressZip" />
                        </el-form-item>
                      </el-col>

                      <el-col :span="12">
                        <el-form-item label="户籍地址">
                          <el-input v-model="row.registrationAddress" />
                        </el-form-item>
                        <el-form-item label="户籍地址邮编">
                          <el-input v-model="row.registrationAddressZip" />
                        </el-form-item>
                        <el-form-item label="工作地址">
                          <el-input v-model="row.workPlace" />
                        </el-form-item>
                        <el-form-item label="工作地址邮编">
                          <el-input v-model="row.workPlaceZip" />
                        </el-form-item>
                        <el-form-item label="紧急联系人">
                          <el-input v-model="row.contact" />
                        </el-form-item>
                        <el-form-item label="联系人电话">
                          <el-input v-model="row.contactPhone" />
                        </el-form-item>
                        <el-form-item label="联系人关系">
                          <el-input v-model="row.relationship" />
                        </el-form-item>
                        <el-form-item label="联系人地址">
                          <el-input v-model="row.contactAddress" />
                        </el-form-item>
                        <el-form-item label="婚姻状态">
                          <el-input v-model="row.marryStatus" />
                        </el-form-item>
                        <el-form-item label="吸烟史">
                          <el-input v-model="row.smokingHistory" />
                        </el-form-item>
                        <el-form-item label="饮酒史">
                          <el-input v-model="row.alcoholHistory" />
                        </el-form-item>
                        <el-form-item label="门诊号">
                          <el-input v-model="row.outpatientNumber" />
                        </el-form-item>
                        <el-form-item label="门诊诊断">
                          <el-input v-model="row.diagnosis" />
                        </el-form-item>
                        <el-form-item label="确诊日期">
                          <el-date-picker
                            v-model="row.dateTime"
                            type="date"
                            placeholder="选择日期"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            style="width:100%"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row :gutter="12">
                      <el-col :span="12">
                        <el-form-item label="疾病编码">
                          <el-input v-model="row.diagnosisCode" />
                        </el-form-item>
                        <el-form-item label="主诉">
                          <el-input v-model="row.chief" />
                        </el-form-item>
                        <el-form-item label="现病史">
                          <el-input v-model="row.presentHistory" type="textarea" :rows="3" />
                        </el-form-item>
                        <el-form-item label="患者自购药物">
                          <el-input v-model="row.selfPurchaseDrugs" />
                        </el-form-item>
                        <el-form-item label="病理诊断">
                          <el-input v-model="row.pathologicalDiagnosis" />
                        </el-form-item>
                        <el-form-item label="疾病编码">
                          <el-input v-model="row.diseaseCode2" />
                        </el-form-item>
                      </el-col>

                      <el-col :span="12">
                        <el-form-item label="病理号">
                          <el-input v-model="row.pathologicalNumber" />
                        </el-form-item>
                        <el-form-item label="损伤中毒">
                          <el-input v-model="row.injuryPoisoning" />
                        </el-form-item>
                        <el-form-item label="损伤中毒-疾病编号">
                          <el-input v-model="row.diseaseCode3" />
                        </el-form-item>
                        <el-form-item label="筛选号">
                          <el-input v-model="row.selectNumber" />
                        </el-form-item>
                        <el-form-item label="筛选日期">
                          <el-date-picker
                            v-model="row.selectDate"
                            type="date"
                            placeholder="选择日期"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            style="width:100%"
                          />
                        </el-form-item>
                        <el-form-item label="入组日期">
                          <el-date-picker
                            v-model="row.joinDate"
                            type="date"
                            placeholder="选择日期"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            style="width:100%"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-card>
              </div>

              <!-- 提交按钮移到表格下面 -->
              <div style="margin-top: 20px; text-align: center;">
                <el-button type="success" :loading="loading" size="medium" @click="submitManual">提交全部</el-button>
              </div>

              <div v-if="manualList.length === 0" style="color:#999;">当前无手动记录，点击「新增一条」开始录入。</div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import { upload, upload_excel } from '@/api/dataEntry/demographicInformation'

export default {
  name: 'DemographicImport',
  data() {
    return {
      loading: false,
      manualList: [],
      // 表单验证规则
      formRules: {
        medicalRecordNumber: [
          { required: true, message: '病案号不能为空', trigger: 'blur' }
        ]
      },
      // 期望字段列表（顺序会用于导出模板）- 调整了字段顺序，病案号放在第三个
      expectedKeys: [
        'number', 'name', 'medicalRecordNumber', 'gender', 'height', 'weight', 'job', 'age', 'phone', 'nationality', 'birthDate', 'birthPlace',
        'ethnicity', 'origin', 'idNumber', 'currentAddress', 'currentAddressZip', 'registrationAddress', 'registrationAddressZip',
        'workPlace', 'workPlaceZip', 'contact', 'contactPhone', 'relationship', 'contactAddress', 'marryStatus', 'smokingHistory',
        'alcoholHistory', 'outpatientNumber', 'diagnosis', 'dateTime', 'diagnosisCode', 'chief',
        'presentHistory', 'selfPurchaseDrugs', 'pathologicalDiagnosis', 'diseaseCode2', 'pathologicalNumber', 'injuryPoisoning',
        'diseaseCode3', 'selectNumber', 'selectDate', 'joinDate'
      ]
    }
  },
  created() {
    // 初始化一条空记录
    this.manualList = [this.getEmptyRecord()]
  },
  methods: {
    getEmptyRecord() {
      const obj = {}
      this.expectedKeys.forEach(k => obj[k] = (k === 'height' || k === 'weight' || k === 'age') ? 0 : '')
      return obj
    },

    addRow() {
      this.manualList.push(this.getEmptyRecord())
    },
    removeRow(idx) {
      this.manualList.splice(idx, 1)
    },

    // 读取 projectId：尝试多个可能的 localStorage 键
    getProjectIdFromLocal() {
      try {
        return localStorage.getItem('CURRENT_PROJECT_ID')
      } catch (e) { /* ignore */ }
      return null
    },

    // 处理上传，直接上传文件
    beforeUpload(file) {
      const name = file.name || (file.raw && file.raw.name) || ''
      const lower = name.toLowerCase()

      if (!lower.endsWith('.xlsx') && !lower.endsWith('.xls')) {
        Message.error('仅支持 xlsx/xls 文件')
        return false
      }

      MessageBox.confirm(`是否开始上传文件 ${name}？`, '确认导入', {
        confirmButtonText: '上传',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.uploadFile(file)
      }).catch(() => {})

      return false
    },

    // 直接上传文件
    async uploadFile(file) {
      const projectId = this.getProjectIdFromLocal()
      if (!projectId) {
        Message.error('未找到 projectId（localStorage），请先在系统中选择或配置项目')
        return
      }

      this.loading = true
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', file)
        // 调用上传接口，假设 upload_excel 支持 FormData
        const resp = await upload_excel({ projectId }, formData)

        const ok = resp && (resp.code === 200)
        if (ok) {
          Message.success('文件上传成功')
        } else {
          const msg = (resp && resp.data && (resp.data.message || resp.data.msg)) || ''
          Message.error('文件上传失败' + (msg ? ('：' + msg) : '，服务器返回异常'))
        }
      } catch (e) {
        Message.error('上传过程中出错：' + (e.message || ''))
      } finally {
        this.loading = false
      }
    },

    // 根据来源调用 upload_excel
    async uploadPayload(payloadArray, source = 'manual') {
      const projectId = this.getProjectIdFromLocal()
      if (!projectId) {
        Message.error('未找到 projectId（localStorage），请先在系统中选择或配置项目')
        return
      }
      this.loading = true
      try {
        const resp = await upload({ projectId }, payloadArray)
        const ok = resp && (resp.code === 200)
        if (ok) {
          Message.success('导入成功')
          // 可选：清空手动列表或执行其它后续操作
        } else {
          const msg = (resp && resp.data && (resp.data.message || resp.data.msg)) || ''
          Message.error('导入失败' + (msg ? ('：' + msg) : '，服务器返回异常'))
        }
      } catch (e) {
        Message.error('上传过程中出错：' + (e.message || ''))
      } finally {
        this.loading = false
      }
    },

    submitManual() {
      if (!this.manualList || !this.manualList.length) {
        Message.error('当前没有可提交的记录')
        return
      }

      // 验证病案号必填
      const badIdx = this.manualList.findIndex(r => !r.medicalRecordNumber || String(r.medicalRecordNumber).trim() === '')
      if (badIdx !== -1) {
        Message.error(`第 ${badIdx + 1} 条记录的病案号不能为空`)
        return
      }

      const payload = this.manualList.map(r => {
        const copy = Object.assign({}, r);
        ['height', 'weight', 'age'].forEach(k => {
          const v = copy[k]
          copy[k] = v === '' || v === null || isNaN(Number(v)) ? 0 : Number(v)
        })
        return copy
      })

      // 手动上传调用 upload
      this.uploadPayload(payload, 'manual')
    },

    resetManual() {
      this.manualList = [this.getEmptyRecord()]
    },

    triggerSampleXlsxDownload() {
      // 后端接口下载
    }
  }
}
</script>

<style scoped>
.page-center {
  display: flex;
  justify-content: center;
}
.medical-form {
  width: 100%;
  max-width: 1100px;
}
.hint { color:#999; }
</style>
